#include <libnl3/netlink/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <netlink/netlink.h>
#include <netlink/genl/genl.h>
#include <netlink/socket.h>

char *rt_type[] = { "TN_UNSPEC",       "RTN_UNICAST", /* Gateway or direct route	*/
		    "RTN_LOCAL", /* Accept locally		*/
		    "RTN_BROADCAST", /* Accept locally as broadcast,
				   send as broadcast */
		    "RTN_ANYCAST", /* Accept locally as broadcast,
				   but send as unicast */
		    "RTN_MULTICAST", /* Multicast route		*/
		    "RTN_BLACKHOLE", /* Drop				*/
		    "RTN_UNREACHABLE", /* Destination is unreachable   */
		    "RTN_PROHIBIT", /* Administratively prohibited	*/
		    "RTN_THROW", /* Not in this table		*/
		    "RTN_NAT", /* Translate this address	*/
		    "RTN_XRESOLVE", /* Use external resolver	*/
		    "_RTN_MAX" };

static int my_func(struct nl_msg *msg, void *arg)
{
	struct rtmsg *rtm = nlmsg_data(nlmsg_hdr(msg));
	printf("recv msg = %s\n", rt_type[rtm->rtm_type]);
	struct nlattr *attr = nlmsg_attrdata(nlmsg_hdr(msg), sizeof(struct rtmsg));

	return 0;
}

struct rtgenmsg rt_hdr = {
	.rtgen_family = AF_UNSPEC,
};

int main()
{
	struct nl_sock *nls = nl_socket_alloc();
	nl_socket_disable_seq_check(nls);
	nl_socket_modify_cb(nls, NL_CB_VALID, NL_CB_CUSTOM, my_func, NULL);

	nl_connect(nls, NETLINK_ROUTE);
	nl_socket_add_memberships(nls, RTNLGRP_LINK, 0);
	nl_send_simple(nls, RTM_GETROUTE, NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr));

	while (1) {
		nl_recvmsgs_default(nls);
	}

	nl_socket_free(nls);
	return 0;
}